package com.quicklife.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * 
 * 关于：
 *	通过 SmartUpload 处理文件的上传，
 *	所有文件名采用IP地址+时间+三位随机数
 * @author AF130310  修改日期：2013-10-19
 *
 */
public class FileFormHandler {
	
	SmartUpload smartUpload = null;
	
	public FileFormHandler(ServletConfig servletConfig, 
			HttpServletRequest request, HttpServletResponse response) {
		smartUpload = new SmartUpload();
		try {
			smartUpload.initialize(servletConfig, request, response);
			smartUpload.upload();
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SmartUploadException e) {
			e.printStackTrace();
		}
	}
	
	public String getParameter(String key) {
		try {
			return URLDecoder.decode(smartUpload.getRequest().getParameter(key), "utf-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}
	
	public Enumeration<String> getParameterNames() {
		return smartUpload.getRequest().getParameterNames();
	}
	
	public JSONObject getParameterJson() {
		JSONObject rqinfos = new JSONObject();
		Request smartRequest = smartUpload.getRequest();
		Enumeration<String> keys = smartRequest.getParameterNames();
		String key = null;
		while (keys.hasMoreElements()) {
			// 与本机环境不符，转
			key = keys.nextElement();
			if (!key.equals("logo") && !key.equals("homepage") && !key.equals("detail")) {
				rqinfos.put(key, getParameter(key));
			}
		}
		return rqinfos;
	}
	
	/**
	 * 处理文件上传，需要注意，需要取出的参数应该在此方法进行前取出
	 * @param dir 文件保存的路径 
	 * @return
	 */
	public String singleFileUpload(String dir) {
		String fileName = null;
		File dirFile = new File(dir);
		if (!dirFile.isDirectory()) {
			dirFile.mkdirs();
		}
		try {
			// 判断文件个数是否大于0
			if (smartUpload.getFiles().getCount() > 0) {
				com.jspsmart.upload.File file = smartUpload.getFiles().getFile(0);
				// 随机名字
				fileName = UUID.randomUUID() + "." + file.getFileExt();
				// 保存文件
				file.saveAs(dirFile.getAbsolutePath()+ java.io.File.separator + fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return fileName;
	}
	
}
